from fastapi.requests import Request
from pydantic import conint

from utils.drivers.database.models.news import News
from utils.enums import Sort, TimeKey
from utils.exception import AppException, StatusCode
from utils.g import G
from utils.i18n.i18n import i18n
from utils.pagination import get_pagination
from utils.template.template import template


async def news_list(request: Request, id_: int = 0, page: conint(ge=1) = 1):
    type_name = i18n(request.state.language, "all")

    if id_ == 0:
        news_items, count = await News.get(page=page, sort=(TimeKey.UpdateTime, Sort.Desc))
    else:
        type_ = [nt for nt in request.state.news_type_list if nt.id == id_]
        if not type_:
            raise AppException(code=StatusCode.NewsTypeNotFound, detail=f"新闻分类`{id_}`不存在。")
        type_ = type_[0]
        type_name = type_.name

        news_items, count = await News.get(news_type=id_, sort=(TimeKey.UpdateTime, Sort.Desc), page=page)

    news_items = [n.model(request.state.language, request.state.product_type_list) for n in news_items]

    pagination = get_pagination(page, G.pageSize, count)

    return template(request, "news_items.html", context={
        "nav": "news",
        "type_id": id_,
        "type_name": type_name,
        "news_items": news_items,
        "pagination": pagination
    })

async def news(request: Request, id_: int):
    n = await News.get_by_id(id_)
    n = n.model(request.state.language, request.state.news_type_list)
    if not n:
        raise AppException(code=StatusCode.NewsByIdNotFound, detail=f"新闻`{id_}`不存在。")

    related_news, _ = await News.get(not_id=n.id, sort=(TimeKey.UpdateTime, Sort.Desc), news_type=n.news_type_id, page_size=6)
    related_news = [rp.model(request.state.language, request.state.news_type_list) for rp in related_news]

    return template(request, "news.html", context={
        "nav": "news",
        "type_id": n.news_type_id,
        "news": n,
        "related_news": related_news,
    })